<template>
  <view class="wrap">

<!--    <u-navbar class="navbar" :is-back="true">-->
<!--      <view class="text">{{pageText}}</view>-->
<!--    </u-navbar>-->

    <u-form :model="model" ref="uForm" :errorType="errorType">
<!--      <u-form-item-->
<!--          label-width="150"-->
<!--          label="店铺类型"-->
<!--      >-->
<!--        <u-input-->
<!--            v-model="store.storeType"-->
<!--            type="text"-->
<!--            disabled-->
<!--        ></u-input>-->


<!--      </u-form-item>-->


<!--      <u-form-item label="商品分类" label-width="150" prop="categoryPath">-->
<!--        <u-input-->
<!--            type="select"-->
<!--            :select-open="actionSheetShow"-->
<!--            v-model="model.categoryName"-->
<!--            placeholder="请选择商品分类"-->
<!--            @click="actionSheetShow = true"-->
<!--        ></u-input>-->
<!--      </u-form-item>-->




      <u-form-item
          label-width="150"
          label="商品名称"
          prop="goodsName"
      >
        <u-input
            placeholder="请输入商品名称"
            v-model="model.goodsName"
            type="text"
        ></u-input>
      </u-form-item>


      <u-form-item
          label-width="150"
          label="计量单位"
          prop="goodsUnit"

      >
        <u-input
            placeholder="请输入计量单位"
            v-model="model.goodsUnit"
            type="select"
            @click="unitShow = true"
        ></u-input>
      </u-form-item>


      <u-form-item
          label-width="150"
          label="商品规格"
          prop="specifications"
      >
        <!--                <u-input-->
        <!--                        placeholder="请创建商品规格"-->
        <!--                        v-model="model.specifications"-->
        <!--                        type="text"-->
        <!--                        @click="onClickShowSpecification"-->
        <!--                ></u-input>-->
        <view @click="onClickShowSpecification">
          <text v-if="model.specifications">{{model.specifications}}</text>
          <text v-else class="placeholder">请创建商品规格</text>
        </view>
      </u-form-item>

      <!--      品牌-->
      <u-form-item
          label-width="150"
          label="品牌"
          prop="brandId"
      >
        <u-input
            placeholder="请输入品牌"
            v-model="model.brandId"
            type="text"
        ></u-input>
      </u-form-item>

      <!--      产地-->
      <u-form-item
          label-width="150"
          label="产地"
          prop="placeOrigin"
      >
        <u-input
            placeholder="请输入产地"
            v-model="model.placeOrigin"
            type="text"
        ></u-input>
      </u-form-item>

      <!--      佣金比例   &#45;&#45;百分比-->
      <u-form-item
          label-width="150"
          label="佣金比例"
          prop="commissionRatio"
      >
        <u-input
            placeholder="请输入佣金比例"
            v-model="model.commissionRatio"
            type="text"
            @input="handleCommissionRatioInput"
        ></u-input>
      </u-form-item>


      <u-form-item
          label="上传音频"
          label-width="150"
      >
        <view v-if="model.goodsVideo">
          <u-button size="mini" type="success" @click="maskShow = true">查看视频</u-button>
        </view>
        <view v-else class="placeholder" @click="onClickUploadGoodsVideo">点击上传音频</view>
      </u-form-item>


      <!--      产品详情intro-->
      <u-form-item
          label-width="150"
          label="产品详情"
          prop="intro"
      >
        <u-input
            placeholder="请输入产品详情"
            v-model="model.intro"
            type="textarea"
        ></u-input>
      </u-form-item>

<!--      <u-form-item-->
<!--          required-->
<!--          :border-bottom="false"-->
<!--          prop="goodsLogo"-->
<!--          label-width="150"-->
<!--          label="产品图片"-->
<!--      >-->
<!--        <div>-->
<!--          <u-upload-->
<!--              :file-list="model.goodsGalleryList"-->
<!--              :header="{ accessToken: storage.getAccessToken() }"-->
<!--              :action="action"-->
<!--              width="200"-->
<!--              @on-uploaded="onUploaded($event, 'goodsGalleryList')"-->
<!--              :max-count="1"-->
<!--              :show-progress="false"-->
<!--          ></u-upload>-->
<!--        </div>
      </u-form-item>

-->


        <u-form-item label-position="left" label="产品图片" label-width="150" required>
          <u-upload
              :custom-btn="true"
              ref="uUpload"
              :auto-upload="true"
              :file-list="model.goodsGalleryList"
              :header="{ accessToken: storage.getAccessToken() }"
              :action="action"
              :max-size="10 * 1024 * 1024"
              max-count="9"
              width="160"
              height="160"
              size-type="['compressed']"
          >
            <view slot="addBtn" class="slot-btn" hover-class="slot-btn__hover" hover-stay-time="150">
              <u-icon name="plus" size="60" :color="$u.color['lightColor']"></u-icon>
            </view>
          </u-upload>
        </u-form-item>




      <!--            <view v-if="model.goodsVideo">-->
      <!--                <video :src="model.goodsVideo" ></video>-->
      <!--            </view>-->

      <!--      <u-form-item-->
      <!--          label="立即发布"-->
      <!--          label-width="150"-->
      <!--      >-->
      <!--        <view class="publish-switch">-->
      <!--          <u-switch v-model="model.release"></u-switch>-->
      <!--        </view>-->
      <!--      </u-form-item>-->

      <!--            -->


    </u-form>

    <u-button v-if="model.goodsId" @click="onClickEditGoods(false)">修改商品</u-button>
    <u-button v-else @click="submit()">发布商品</u-button>

    <u-popup v-model="specificationShow" mode="bottom" border-radius="14" length="70%">

      <view class="specification-popup-content">
        <scroll-view class="scroll-view" scroll-y="true"  >
          <view class="specification-content">
            <view>
              <view v-for="(item1, index1) in skuInfo" class="specification-item">
                <u-row>
                  <u-col span="8">
                    <u-input v-model="item1.name" type="select" placeholder="请选择规格" :border="true" @click="onclickChoiceSpec(index1)"/>
                  </u-col>
                  <u-col span="1"/>
                  <u-col span="3">
                    <u-button type="warning" plain @click="onClickDeleteSpecification(index1)">删除规格</u-button>
                  </u-col>
                </u-row>

                <view>
                  <view v-for="(item2, index2) in item1.spec_values" class="specification-item-spec">
                    <u-row>
                      <u-col span="2">
                        <view>规格项</view>
                      </u-col>
                      <u-col span="5">
                        <u-input v-model="item2.value" type="text" placeholder="请输入规格项" :border="true" />
                      </u-col>
                    </u-row>

                    <u-row>
                      <u-col span="2">
                        <view>价格</view>
                      </u-col>
                      <u-col span="5">
                        <u-input v-model="item2.price" type="text" placeholder="请输入价格" :border="true" />
                      </u-col>
                      <u-col span="2"/>
                    </u-row>

                    <u-row>
                      <u-col span="2">
                        <view>库存</view>
                      </u-col>
                      <u-col span="5">
                        <u-input v-model="item2.quantity" type="number" placeholder="请输入库存" :border="true" />
                      </u-col>
                      <u-col span="2"/>
                      <u-col span="3">
                        <u-button type="warning" plain @click="onClickDeleteSpec(index1, index2)">删除</u-button>
                      </u-col>
                    </u-row>

                  </view>
                  <u-button type="success" plain @click="onClickAddSpec(index1)">添加规格项</u-button>
                </view>
              </view>
            </view>
            <!--                        <view>-->
            <!--                            <u-button type="primary" plain @click="onClickAddSpecification">添加规格</u-button>-->
            <!--                        </view>-->
          </view>
        </scroll-view>
        <view class="enter-button">
          <u-button type="success" @click="onClickEnterSpecification">确定</u-button>
        </view>
      </view>
    </u-popup>

    <u-picker v-model="unitShow" mode="selector" :range="goodsUnitList" range-key="name" @confirm="onClickUnit"></u-picker>
    <u-picker v-model="templateShow" mode="selector" :range="templateList" range-key="name" @confirm="onClickTemplate"></u-picker>
    <u-picker v-model="specShow" mode="selector" :range="specificationList" range-key="specName" @confirm="onClickSpecification"></u-picker>

    <u-mask :show="maskShow"
            @click="maskShow = false">
      <view v-if="maskShow" class="mask-content">
        <video :src="model.goodsVideo" ></video>
      </view>
    </u-mask>

    <u-modal v-model="showModal"
             :show-cancel-button="true"
             :mask-close-able="true"
             @cancel="maskShow = false"
             @confirm="onClickEnternDeleteImage">
      <view class="modal-text">{{modalContent}}</view>
    </u-modal>

    <u-action-sheet
        :list="actionSheetList"
        v-model="actionSheetShow"
        @click="actionSheetCallback"
    ></u-action-sheet>

    <u-toast ref="uToast" />
  </view>
</template>

<script>
import storage from "@/utils/storage.js";
import {upload} from "@/api/common.js";
import config from "@/config/config";
import { saveGoods,getCategoryList2 } from "@/api/goods.js";
export default {
  name: "shelves",
  data(){
    return{
      storage,
      config,
      store:{},
      categoryList:[],
      pageText: "",
      action: upload, //图片上传数据
      deleteImageIndex: -1,
      // 需要提交的规格项
      showModal: false,
      modalContent: "",
      isCreate: false,
      actionSheetList:[],
      actionSheetShow: false,
      categoryName:"",
      skuInfo: [],
      jsonData:{},
      upload: upload,
      specShow: false,
      unitShow: false,
      maskShow: false,
      templateShow: false,
      specificationShow: false,
      goodsUnitList:[
        { name: "个", id: 1 },
        { name: "件", id: 2 },
        { name: "只", id: 2 },
        { name: "箱", id: 2 },
        { name: "包", id: 3 }
      ],
      templateList:[],
      specificationList:[
        { specName: "颜色", id: 1 },
        { specName: "尺寸", id: 2 },
        { specName: "材质", id: 3 },
        { specName: "服务", id: 3 }
      ],
      params: {},
      skuList_index: -1,
      model: {
        skuList:[{
          images:[]
        }],
        release: true,
        templateName: "",
        original: "",
        goodsVideo: "",
        goodsGalleryList:[],
        goodsType: "PHYSICAL_GOODS",
        weight: 1,
        specifications: "",
        categoryPath:"",
        categoryName:"",
        categoryId:"",
        price: "0.01",
        placeOrigin:"",
        brandId:"",
        intro:"",
        goodsId: null,
        goodsName:"",
        goodsUnit:"",
        commissionRatio:0

      },
      errorType: ["message"],
      rules: {
        categoryPath:[
          {
            required: true,
            message: "请选择商品分类",
            trigger: "blur",
            transform(value){
              return String(value)
            },
          }
        ],
        goodsName: [
          {
            required: true,
            message: "请输入商品名称",
            trigger: "blur",
            transform(value){
              return String(value)
            },
          },
          {
            min: 3,
            max: 14,
            message: "商品名称长度必须在3~14之间",
            trigger: ["change", "blur"],
          },
        ],
        commissionRatio: [
          {
            required: true,
            message: "请输入佣金比例",
            trigger: "blur",
            transform(value){
              return String(value)
            },
          },
          {
            min: 0,
            max: 100,
            message: "佣金比例必须在0~100之间",
            trigger: ["change", "blur"],
          },
        ],
        goodsUnit:[
          {
            required: true,
            message: "请选择计量单位",
            trigger: "blur",
            transform(value){
              return String(value)
            },
          }
        ],
        specifications:[
          {
            required: true,
            message: "请创建商品规格",
            trigger: "blur",
            transform(value){
              return String(value)
            },
          }
        ],
        quantity:[
          {
            required: true,
            message: "请输入库存数量",
            trigger: "blur",
          }
        ]

      }
    }
  },
  onReady() {
    this.$refs.uForm.setRules(this.rules);
  },
  onLoad(options){

    uni.setNavigationBarColor({
      frontColor: '#000000',
      backgroundColor: '#FFF',
      animation: {
        duration: 400,
        timingFunc: 'easeIn'
      }
    })

    var  store=uni.getStorageSync("store");
    this.store=store;

    this.getCategoryList(store.storeTypeId);


    this.model.categoryId = options.categoryId;
   // this.model.categoryName = options.categoryName;
    //this.selectCategoryByParentId();
    if (options.goodsId){
      this.pageText = "修改商品";
      this.model.goodsId = options.goodsId;
      // 模拟获取商品信息
      this.getGoodsByGoodsId(options.goodsId);
    }else{
      this.pageText = "发布商品";
      this.model.stallId = options.stallId;
      this.init();
    }
  },

  methods:{
    getCategoryList(pid){
      getCategoryList2(pid).then(res=>{
        if (res.data.code==200){
          this.categoryList=res.data.result;

          this.actionSheetList=[];
          this.categoryList.forEach((item) => {
            var vo={
              text: item.name,
              value: item.id
            };
            this.actionSheetList.push(vo);
          });

        }
      })
    },
    // 图片上传
    onUploaded(lists, key) {

      let images = [];
      lists.forEach((item) => {
        images.push(item.response.result);
      });
      this.model[key] = images;

     this.model.goodsGalleryList = images

    },
    submit() {

      if (this.isButtonDisabled) return;

      this.$refs.uForm.validate((valid) => {
        if (!valid) {
          return;
        }

        let files = [];
        // 通过filter，筛选出上传进度为100的文件(因为某些上传失败的文件，进度值不为100，这个是可选的操作)
        files = this.$refs.uUpload.lists.filter(val => {
          return val.progress == 100;
        })
        if (this.$u.test.isEmpty(files)) {
          uni.showToast({
            title: "请至少选择一张房源图片",
            icon: "none",
          });
          return
        }
       files.map(val => {
          if (undefined != val.response) {
            this.model.goodsGalleryList.push(val.response.result)
          }
        })

        saveGoods(this.model).then((result) => {
          if (result.data.code === 200) {

            this.isButtonDisabled = true;

            // 设置定时器，5秒后重新启用按钮
            this.timer = setTimeout(() => {
              this.isButtonDisabled = false;
            }, 5000);


            this.$u.route({
              url: '/pages/product/shopPage?storeId='+this.store.id,
            });

          } else {
            uni.showToast({
              title: result.data.msg,
            });
          }
        });
      });
    },
    onClickEnternDeleteImage(){

      this.model.goodsGalleryList.splice(this.deleteImageIndex, 1)
    },

    onClickShowSpecification(){
      this.specificationShow = true;
    },

    // 模拟获取商品信息
    getGoodsByGoodsId(goodsId){
      // 模拟数据
      var goodsInfo = {
        goodsName: "示例商品",
        sellingPoint: "这是一个示例商品的卖点",
        goodsUnit: "个",
        goodsGalleryList: [],
        twoCategoryName: "示例二级分类",
        goodsVideo: ""
      };
      var skuList = [
        {
          specId: 1,
          name: "颜色",
          specVOList: [
            {
              value: "红色",
              price: "10.00",
              quantity: 10
            }
          ]
        }
      ];

      this.model.goodsName = goodsInfo.goodsName;  // 商品名称
      this.model.sellingPoint = goodsInfo.sellingPoint;  // 卖点
      this.model.goodsUnit = goodsInfo.goodsUnit;  // 计量单位

      this.model.goodsGalleryList = goodsInfo.goodsGalleryList;

      //this.model.categoryName = goodsInfo.twoCategoryName;
      this.model.categoryPath = goodsInfo.goodsInfo;
      this.model.goodsVideo = goodsInfo.goodsVideo;
      this.model.specifications = "颜色";
      skuList.forEach(skuItem =>{
        let sku = {
          specId: skuItem.specId,
          name: skuItem.name,
          spec_values: skuItem.specVOList
        };
        this.skuInfo = this.skuInfo.concat(sku);
      });
    },

    actionSheetCallback(index) {
      uni.hideKeyboard();
      // this.categoryName = this.actionSheetList[index].text;
      this.model.categoryName = this.actionSheetList[index].text;
      this.model.categoryId = this.actionSheetList[index].value;
      this.model.categoryPath =this.store.storeTypeId +","+this.actionSheetList[index].value;

    },
    selectCategoryByParentId(){
      //  var that=this;
      // 模拟数据
      // var categoryList = [
      //   { name: "示例二级分类1", id: 1 },
      //   { name: "示例二级分类2", id: 2 }
      // ];
      // that.actionSheetList=[];
      // that.categoryList.forEach((item) => {
      //   var vo={
      //     text: item.name,
      //     value: item.id
      //   };
      //
      //   that.actionSheetList.push(vo);
      //
      // });
    },
    // 初始化数据
    init(){
      this.skuInfo.push({
        name: this.specificationList[0].specName,
        spec_values: [
          {
            price: "0.00",
            sn: "",
            quantity: 0,
            images: "",
            value: ""
          }
        ]
      })
    },

    // 添加规格
    onClickAddSpecification(){
      this.skuInfo.push({
        specId: "",
        name:"",
        spec_values: [{
          price: "",
          sn: "",
          quantity: null,
          images: "",
          // weight: 0,
          value: "",
        }],
      })
    },

    // 删除规格
    onClickDeleteSpecification(index){
      if (this.skuInfo[index].length == 1){
        this.$refs.uToast.show({
          title: "规格不可删除",
          type: "error",
        })
        return;
      }
      this.skuInfo.splice(index, 1);
    },

    // 添加规格项
    onClickAddSpec(index){
      this.skuInfo[index].spec_values.push({
        price: "",
        sn: "",
        quantity: null,
        images: "",
        // weight: 0,
        value: "",
      })
    },

    // 删除规格项
    onClickDeleteSpec(index1, index2){
      if (this.skuInfo[index1].spec_values.length == 1){
        this.$refs.uToast.show({
          title: "规格项不可删除",
          type: "error",
        })
        return;
      }
      this.skuInfo[index1].spec_values.splice(index2, 1);
    },

    // 确认创建规格
    onClickEnterSpecification(){
      let result = true;
      let specifications = "";
      let sukList = [];
      this.skuInfo.forEach(item1 =>{
        if (item1.name === "" || item1.name == null){
          this.$refs.uToast.show({
            title: "未选择规格",
            type: "warning",
          });
          result = false;
          return;
        }
        item1.spec_values.forEach(item2 =>{
          if (item2.value === "" || item2.value == null){
            this.$refs.uToast.show({
              title: "未填写规格项",
              type: "warning",
            });
            result = false;
            return;
          }
          if (item2.price === "" || item2.price == null){
            this.$refs.uToast.show({
              title: "未填写价格",
              type: "warning",
            });
            result = false;
            return;
          }
          if (item2.quantity == null || item2.quantity.length == 0){
            this.$refs.uToast.show({
              title: "规格项 " + item2.value + "未填写库存",
              type: "warning",
            });
            result = false;
            return;
          }
          let suk = {
            specId: item1.specId,
            specName: item1.name,
            price: item2.price,
            quantity: item2.quantity,
            weight: 1,
            images:[]
          };
                    this.model.goodsGalleryList.forEach(item3 =>{
            suk.images.push({
              url: item3
            })
          })
          suk[item1.name] = item2.value;
          sukList.push(suk);
        });
        specifications = specifications + item1.name + ","
      })
      if (result){
        this.model.skuList = sukList;
        specifications = specifications.substring(0, specifications.length - 1);
        this.model.specifications = specifications;
        this.specificationShow = false;
      }
    },

    //选择规格
    onclickChoiceSpec(index){
      this.specShow = true;
      this.skuList_index = index;
    },

    // 点击规格
    onClickSpecification(index){
      this.skuInfo[this.skuList_index].name = this.specificationList[index].specName;
      this.skuInfo[this.skuList_index].specId = this.specificationList[index].id;
    },

    // 点击选择物流模板
    onClickTemplate(index){
      this.model.templateName = this.templateList[index].name;
      this.model.templateId = this.templateList[index].id;
    },

    onClickEditGoods(status){

      this.onClickEnterSpecification();
      this.$refs.uForm.validate((valid) => {
        if (valid) {
          let func = null;
          let title = "";
          if (status){
            // title = "商品发布中..."
            // func = function() {
            //   return new Promise((resolve) => {
            //     resolve({
            //       data: {
            //         success: true
            //       }
            //     });
            //   });
            // };


          }else{
            title = "商品修改中..."
            func = function() {
              return new Promise((resolve) => {
                resolve({
                  data: {
                    success: true
                  }
                });
              });
            };
          }

          uni.showLoading({
            title: title
          });
          this.model.recommend = false;
          var jsonDataStr = JSON.stringify(this.model);
          setTimeout(()=>{
            func(jsonDataStr).then(res=>{
              if (res.data.success){
                let pages = getCurrentPages(); // 获取当前页面栈的实例，以数组形式按栈的顺序给出，第一个元素为首页，最后一个元素为当前页面。
                let prevPage = pages[pages.length - 2]; //上一页页面实例
                uni.navigateBack({
                  delta:1,
                  success:() => {
                    prevPage.$vm.goBack() // 给上一页绑定方法otherFun,传参地址id
                  }
                })
              }
              uni.hideLoading();
            }, 1000)
          })
        }
      });
    },



    // 上传视频
    onClickUploadGoodsVideo() {
      var that = this;
      // 选择文件
      uni.chooseVideo({
        sourceType: ['album', 'camera'],
        maxDuration: 20,
        camera: 'back',
        success: function(res) {
          if (res.size > 10 * 1024 * 1024) {
            uni.showToast({
              title: '请选择不大于10M的视频上传',
              icon: 'none'
            })
            return
          }


          // 选择成功，开始上传文件
          uni.showLoading({
            title: '上传中...'
          });
          // 模拟上传成功
          setTimeout(() => {
            that.model.goodsVideo = "https://example.com/video.mp4";
            uni.showToast({
              title: '上传成功'
            });
            uni.hideLoading();
          }, 1000);
        }
      });
    },
    // 点击选择计量单位
    onClickUnit(index){
      this.model.goodsUnit = this.goodsUnitList[index].name;
      this.model.goodsUnitId = this.goodsUnitList[index].id;
    },
    // 处理佣金比例输入
    handleCommissionRatioInput(event) {
      let value = parseFloat(event.target.value);
      if (isNaN(value)) {
        this.model.commissionRatio = '';
        return;
      }
      if (value < 0) {
        this.model.commissionRatio = 0;
      } else if (value > 100) {
        this.model.commissionRatio = 100;
      } else {
        this.model.commissionRatio = value;
      }
    }
  }
}
</script>

<style scoped lang="scss">


.wrap {

  .upload-goods-image-list > view{
    display: inline-block;
  }

  .navbar{
    .text{
      text-align: center;
      width: 100%;
      font-size: 16px;
      font-weight: bold;
    }

  }

  .modal-text{
    text-align: center;
    padding: 30px;
  }
  padding: 30rpx;
  position: relative;
  .mask-content{
    display: flex;
    align-items: center;
    height: 100%;
  }
  .specification-popup-content{
    position: relative;
    height: 100%;
    padding: 10px;
    .specification-content{
      height: 500px;
      .specification-item{
        border: 1px solid rgba(0, 0, 0, 0.26);
        padding: 10px;
        border-radius: 8px;
        border-radius: 8px;
        margin-bottom: 10px;
        .specification-item-spec{
          border: 1px solid rgba(0, 0, 0, 0.26);
          padding: 10px;
          border-radius: 8px;
          margin-bottom: 2px;
        }
      }
    }
    .enter-button{
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
    }
  }

  .uni-scroll-view{
    background-color: red!important;
  }

  .upload-goods-image{
    margin-right: 10rpx;
  }
  .upload-goods-image > image{
    width: 160rpx;
    height: 160rpx;
    border-radius: 10rpx;
  }

  .publish-switch{
    margin-left: auto;
    display: flex;
  }

  .placeholder{
    color: #89898982;
  }


}

uni-video{
  width: 100%!important;
  height: 200px!important;
}


</style>